// pages/goodsDetail/goodsDetail.js
var util = require('../../utils/util.js');
var app = getApp();
// 关注他人的接口地址
const attentionUri = "/User/attentionShop";
//免费领接口
const freeGetGoodsUri = "/Goods/freeGetGoods";
const GoodsDetailImagePosterUri = "/GoodsDetailImage/getPoster";
const addCarUrl = "/ShopCart/joinCart";
// 立即购买接口地址
const buyImmediatelyUrl = '/Order/buyGoods';
// 获取二维码图片的接口地址
const getQRCodeImgUrl = '/GoodsQrCode/getQrCode';
//移除数组中的元素
Array.prototype.remove = function(val) {
  var index = this.indexOf(val);
  if (index > -1) {
    this.splice(index, 1);
  }
}
//检测指定的值是否存在
Array.prototype.in_array = function(element) {
  for (var i = 0; i < this.length; i++) {
    if (this[i] == element) {
      return true;
    }
  }
  return false;
}
//计算差集
Array.prototype.difference = function(arr) {
  var result = new Array();
  var obj = {};
  for (var i = 0; i < arr.length; i++) {
    obj[arr[i]] = 1;
  }
  for (var j = 0; j < this.length; j++) {
    if (!obj[this[j]]) {
      obj[this[j]] = 1;
      result.push(this[j]);
    }
  }
  return result;
}
Page({

  /**
   * 页面的初始数据
   */
  data: {
    displayAuthShow: 0,//控制授权弹层的显示和隐藏
    user_nick: '',//用户昵称
    user_image: '',//用户头像
    service_goods_detail_is_show:0,//客服是否显示
    service_content:'',//客服描述
    service_reply_btn_title:'',//客服按钮文案
    isLoading: 1, //是否显示加载中图标
    clickNum: 0, //点击次数
    isClick: 1, //是否可以点击
    is_show_buy_btn: '', //是否显示立即购买按钮
    bargain_buy_title: '', //1分砍价按钮文案
    draw_buy_title:'',//抽奖按钮文案 
    is_bargain: 0, //判断是否为砍价商品
    is_vip_goods: 0, //是否是会员商品
    is_open_shop: 0, //是否是开通会员的商品
    lucky_rule:'',//抽奖规则数组
    attributeImage: '', //选取商品尺码的盒子左上角图片
    cash: [], //优惠券列表
    idolId: 0, //当前用户的爱豆ID
    QRCodeImg: '', //二维码图片地址
    QRCodeImgHttp: '', //http二维码图片地址
    isUseHttp: 0, //判断是否使用http
    isHasChoosed: 0, //判断当前页面是否弹出过选择尺寸的弹层
    full_money: '', //店铺的满减金额
    user_level: 0, //用户的身份
    selectAttributeprice: 0.00, //初始化选择商品规格的优品价格
    attr_original_pric: 0.00, //初始化选择商品的原价
    attr_fans_pric: 0.00, //初始化选择商品规格的粉丝价格
    attr_vip_pric: 0.00, //初始化选择商品规格的会员价格
    attr_broker_pric: 0.00, //用户赚的价格
    runSelectTips: [], //
    selectedAttributs: [], //已经选择过的商品属性列表
    goodsAttibutes: [], //商品属性的列表
    isShareMaskShow: 0, //控制分享弹层的显示
    isQRCodeMaskShow: 0, //控制分享二维码弹层的显示
    car_shop_num: 0, //购物车里面的商品数量
    shop_cart_is_show: 0, //控制购物车的显示或者隐藏
    express_type: 0, //运输方式
    freight: 0, //商品运费
    is_draw: 0, //判断是否包邮
    buy_price: 0, //优品价
    fans_price: 0.00, //专属粉丝价
    vip_price: 0.00, //会员价
    goods_page_top_adv_is_show: 0, //控制广告位的显示和隐藏
    auction_gold_coin: 505, //初始化用户出价的金币
    is_kf_mask_show:0,//控制客服弹层的显示
    isBiddersShow: 0, //控制竞拍盒子的显示
    gold_coin: 0, //商品需要的金币数
    user_gold_coin: 0, //用户剩余的金币数
    wx_uuid: 4, //被关注者ID
    isShareTipsShow: 0, //控制分享提示弹层的显示和隐藏
    lucky_rule: [], //存放抽奖规则
    send_msg: '', //领取的状态提示
    send_status: 0, //领取的状态码
    free_is_show: 0, //判断在搞活动期间是否要显示免费领取按钮
    goodsId: 0, //商品ID
    goods_level: 4, //商品类型
    confirm_is_show: 0, //控制领取成功弹层的显示和隐藏
    goodsList: [],
    page: 1, //商品推荐页码
    share_title: '', //分享标题
    share_img: '', //分享图片
    share_path: '', //分享后访问的路径
    original_price: 0.00, //商品原价
    get_num: 0, //领取的人数
    name: '', //商品名称
    total_num: 0, //商品总个数，0代表缺货
    share_num: 0, //需要分享的次数
    carousel_img: [], //轮播图数组
    robot_list: [], //机器人列表
    goodsNum: 1, //用户选择商品的数量
    isHelpFreeShow: 0, //控制助力免费领弹层显示
    isResultMaskShow: 0, //控制活动规则弹层显示
    ischooseSizeShow: 0, //控制选取尺寸盒子的显示
    index: 1, //存储顶部轮播图的索引
    ruleList: [], //活动规则列表
    configs: {},
    fileStaticUri: "", //资源文件存放地址
    initThumb: "", //详情默认缩略图
    content: '每人限领1件哦~',
    btnType: '0', //弹出属性弹层状态 0 表示直接购买 1 表示分享后购买
    default_address: 0, //是否已激活地址  0 表示未激活  1表示已激活
    get_type: 0, //表示没有属性 其他表示有属性
    lucky_id: '', //奖品ID
    draw_goods_id: '', //奖品所属商品id
    gold_coin: 0, //金币数
    gold_num_tips: '', //分享提示
    gold_share_default_tips: '分享获得金币', //默认分享金币提示
    helpBoxShow: 0, //助理邀请好友谈层
    user_gold_coin: 0, //我的金币数
    auction_status: 0, //竞拍状态 0 未开始 1 竞拍中 2 竞拍结束
    auction_end_time: 0, //竞拍结束时间
    address_default: 0, //是否有默认地址
    is_edit: 0, //是否可以编辑商品（商品发布后提交到后台的审核状态显示为1）
    is_self: 0, //商品是否属于本人发布 默认为 0 非本人发布 该 参数可配合is_edit一起使用
    is_attention: 0, //是否关注过 0 默认未关注过
    is_shunfeng: 0, // 是否仅限顺丰
    goods_name: "", //  商品名称
    goods_describe: "", //商品描述
    province_name: "", //商品第一级地址
    shop_nick_name: "", //商家昵称
    shop_img: "", //商家头像
    detail_img: [], //商品描述
    help_user_list: [], //已帮助助力人
    unhelp_user_list: [], //剩余助力人数
    confirm_is_show: 0, //助力成功谈层是否显示
    confirm_data: {}, //助力成功谈层信息
    residue_help_num: 1, //剩余助力需要的人数
    help_num: 0, //助力需要的总人数
    share_uid: 0, //需要助力的用户id
    is_platform: 0, //商品是否属于平台
    orderId: 0, //订单编号
    lucky_rule: [], //抽奖规则介绍
    is_draw: 1, //是否为抽奖商品
    deduct_gold_coin: 0 // 扣除用户的金币数
  },
  // 关闭客服弹层
  closeKfmask:function(){
    this.setData({
      is_kf_mask_show:0
    });
  },
  // 打开客服弹层
  openKfmask:function(){
    this.setData({
      is_kf_mask_show: 1
    });
  },
  // 商品库存不足提示
  tipsOfGoodsNum: function() {
    wx.showToast({
      title: '该属性库存不足，请重新选择',
      duration: 2000,
      icon: "none"
    })
  },
  // 跳转会员支付页面
  goVipRecharge: function() {
    wx.navigateTo({
      url: '/pages/vipRecharge/vipRecharge',
    })
  },
  // 阻止点击事件
  preventEvent: function() {},
  // 跳转现金券页面
  goCashCoupon: function() {
    wx.navigateTo({
      url: '/pages/cashCoupon/cashCoupon?uid=' + this.data.idolId,
    })
  },
  // 跳转95折页面
  goCoupon: function() {
    wx.navigateTo({
      url: '/pages/coupon/coupon',
    })
  },
  // 点击卖商品按钮
  sellGoods: function() {
    this.setData({
      isShareMaskShow: 1
    })
  },
  // 关闭分享弹层
  closeShareMask: function() {
    this.setData({
      isShareMaskShow: 0
    })
  },
  // 判断商品是否选择过属性
  isChooseSize: function() {
    var _this = this;
    var selectedAttributs = _this.data.selectedAttributs;
    var goodsAttibutes = _this.data.goodsAttibutes;
    if (goodsAttibutes.length != 0 && selectedAttributs.length == 0) {
      var ischooseSizeShow = _this.data.ischooseSizeShow;
      if (ischooseSizeShow == 1) {
        _this.refreshTips();
        wx.showToast({
          title: _this.data.selectTipsTitle + _this.data.selectTips,
          duration: 2000,
          icon: "none"
        })
      }
      _this.setData({
        ischooseSizeShow: 1
      })
      return false;
    } else {
      return true;
    }
  },
  /*刷新选择提示内容*/
  refreshTips: function() {
    var _this = this;
    var runSelectTips = _this.data.runSelectTips;
    var tips = "属性";
    runSelectTips.forEach((v, index) => {
      if (v.is_selected == 0) {
        tips = tips + " " + v.attr_name
      }
    });
    _this.setData({
      selectTips: tips,
      selectTipsTitle: "请选择"
    });
  },
  // 加入购物车
  addCar: function(e) {
    var _this = this;
    var formId = e.detail.formId;
    app.postFormId(_this.data.token, formId);
    var chooseSize = _this.isChooseSize();
    var goodsAttibutes = _this.data.goodsAttibutes;
    var requestData;
    if (chooseSize) {
      if (goodsAttibutes.length == 0) {
        requestData = {
          version: app.setConfig.version,
          token: _this.data.token,
          type: app.setConfig.type,
          goods_id: _this.data.goodsId,
          num: _this.data.goodsNum,

        };
      } else {
        var attr_thumb = _this.data.attributeImage;
        var subStr = new RegExp('http://source.xingliaoapp.com/');
        attr_thumb = attr_thumb.replace(subStr, "");
        requestData = {
          version: app.setConfig.version,
          token: _this.data.token,
          type: app.setConfig.type,
          goods_id: _this.data.goodsId,
          attr_values: _this.data.selectAttributs,
          attr_thumb: attr_thumb,
          attr_pric: _this.data.selectAttributeprice,
          attr_vip_pric: _this.data.attr_vip_pric,
          attr_fans_pric: _this.data.attr_fans_pric,
          attr_broker_pric: _this.data.attr_broker_pric,
          goods_attr_id: _this.data.goods_attr_id,
          num: _this.data.goodsNum
        };
      }
      app.post(addCarUrl, requestData, function(res) {
        if (res.code != 2000) {
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 2000
          })
        } else {
          var car_shop_num = _this.data.car_shop_num + requestData.num;
          _this.setData({
            car_shop_num: car_shop_num++,
            ischooseSizeShow: 0,
            selectedAttributs: [],
            goodsAttibutes: _this.data.goodsAttibutesData
          })
          wx.showToast({
            title: '加入购物车成功',
            icon: 'none',
            duration: 2000
          })
        }
      });
    }
  },
  // 立即购买
  buyImmediately: function(e) {
    var _this = this;
    var isHasAddres = _this.checkAddress(0);
    var chooseSize = _this.isChooseSize();
    var goodsAttibutes = _this.data.goodsAttibutes;
    var responseData;
    var is_bargain = 1;
    var clickNum = _this.data.clickNum;

    if (e.currentTarget.dataset.is_bargain == 0) {
      is_bargain = 0;
    }
    if (goodsAttibutes.length == 0) {
      _this.setData({
        isClick: 0
      })
      responseData = {
        version: app.setConfig.version,
        token: _this.data.token,
        type: app.setConfig.type,
        goods_id: _this.data.goodsId,
        goods_num: _this.data.goodsNum
      };
    } else {
      clickNum = clickNum + 1;
      console.log(clickNum);
      _this.setData({
        clickNum: clickNum
      })
      var attr_thumb = _this.data.attributeImage;
      var subStr = new RegExp('http://source.xingliaoapp.com/');
      attr_thumb = attr_thumb.replace(subStr, "");
      responseData = {
        is_bargain: is_bargain,
        version: app.setConfig.version,
        token: _this.data.token,
        type: app.setConfig.type,
        goods_id: _this.data.goodsId,
        attr_values: _this.data.selectAttributs,
        attr_thumb: attr_thumb,
        attr_pric: _this.data.selectAttributeprice,
        attr_vip_pric: _this.data.attr_vip_pric,
        attr_fans_pric: _this.data.attr_fans_pric,
        attr_broker_pric: _this.data.attr_broker_pric,
        goods_attr_id: _this.data.goods_attr_id,
        goods_num: _this.data.goodsNum
      };
    }
    console.log(isHasAddres, chooseSize);
    if (isHasAddres) {
      if (chooseSize) {
        if (clickNum >= 2) {
          _this.setData({
            isClick: 0
          })
        }
        _this.setData({
          isHasChoosed: 1
        })
        app.post(buyImmediatelyUrl, responseData, function(res) {
          if (res.code == 2000) {
            _this.setData({
              isClick: 1,
              clickNum: 0
            })
            var is_jump_order = res.data.is_jump_order;
            if (is_jump_order==0){
              wx.navigateTo({
                url: '/pages/bargain/bargain?uid=0'+ '&order_id=' + res.data.order_id,
              })
            } else if (is_jump_order == 1){
              wx.navigateTo({
                url: '/pages/orderDetail/orderDetail?orderId=' + res.data.order_id,
              })
            }else if (is_jump_order == 2) {
              wx.navigateTo({
                url: '/pages/draw/draw?uid=0' + '&order_id=' + res.data.order_id,
              })  
            }
          } else {
            wx.showToast({
              title: res.msg,
              duration: 2000,
              icon: "none"
            })
          }
        })
      }
    }
  },
  // 跳转聊天页面
  goChat: function(e) {
    var _this = this;
    var formId = e.detail.formId;
    app.postFormId(_this.data.token, formId);
    wx.navigateTo({
      url: '/pages/chat/chat?goodsId=' + _this.data.goodsId + '&shopId=' + _this.data.shopId,
    })
  },
  // 跳转购物车页面
  goMyShopCar: function(e) {
    var _this = this;
    var formId = e.detail.formId;
    app.postFormId(_this.data.token, formId);
    wx.reLaunch({
      url: '/pages/buyCar/buyCar',
    })
  },
  // 赠一得一确定按钮

  sendSure: function() {
    var _this = this;
    _this.setData({
      confirm_is_show: 0
    })
    var requestData = {
      version: app.setConfig.version,
      token: _this.data.token,
      type: app.setConfig.type,
      goods_id: _this.data.goodsId,
      give_type: _this.data.confirm_type
    }
    app.post('/Goods/giveConfirm', requestData, function(res) {
      if (res.code != 2000) {
        wx.showToast({
          title: res.msg,
          icon: 'none',
          duration: 2000
        })
      }
    })
  },
  // 助力免费领确定兑换商品
  helpFreeSure: function() {
    var _this = this;
    _this.setData({
      isHelpFreeShow: 0
    });
    var requestData = {
      version: app.setConfig.version,
      token: _this.data.token,
      type: app.setConfig.type,
      goods_id: _this.data.goodsId
    }
    app.post('/Help/confirm', requestData, function(res) {
      if (res.code != 2000) {
        wx.showToast({
          title: res.msg,
          icon: 'none',
          duration: 2000
        })
      } else {
        wx.showToast({
          title: res.msg,
          icon: "none",
          duration: 2000
        });
      }
    })
    _this.loop();
  },
  // 前往助力免费领页面
  goHelpFreee: function(e) {
    var _this = this;
    var formId = e.detail.formId;
    app.postFormId(_this.data.token, formId);
    var confirm_is_show = _this.data.confirm_is_show;
    if (confirm_is_show == 1) {
      _this.setData({
        isHelpFreeShow: 1
      })
    } else {
      wx.navigateTo({
        url: '/pages/helpFree/helpFree?goods_id=' + _this.data.goodsId,
      })
    }

  },
  // 前往赠送页面
  goSend: function(e) {
    var _this = this;
    var formId = e.detail.formId;
    app.postFormId(_this.data.token, formId);
    wx.navigateTo({
      url: '/pages/send/send?goods_id=' + _this.data.goodsId,
    })
  },
  // 关闭出价盒子弹层
  closeBidders: function() {
    var _this = this;
    _this.setData({
      isBiddersShow: 0
    })
  },
  // 关闭选取尺寸盒子
  closeChooseSize: function() {
    var _this = this;
    _this.setData({
      ischooseSizeShow: 0,
      selectTipsTitle: "请选择",
      selectAttributs: "",
      selectTips: "",
      selectedAttributs: []
    })
  },
  // 关闭规则弹层
  closeRuleMask: function() {
    var _this = this;
    _this.setData({
      isResultMaskShow: 0
    })
  },
  // 关闭赠一得一领取失败弹层
  closeReceiveFailMask: function() {
    var _this = this;
    _this.setData({
      send_status: 0
    })
  },
  // 关闭赠一得一赠送成功弹层
  closeSendMask: function() {
    var _this = this;
    _this.setData({
      confirm_is_show: 0
    })
  },
  // 关闭赠一得一领取成功弹层
  closeReceiveMask: function() {
    var _this = this;
    _this.setData({
      send_status: 0
    })
  },

  // 关闭助力免费领弹层
  closeHelpFreeMask: function() {
    var _this = this;
    _this.setData({
      isHelpFreeShow: 0
    })
  },
  // 点击竞拍免费领按钮显示竞拍盒子
  biddersOffer: function() {
    var _this = this;
    _this.setData({
      isBiddersShow: 0
    })
  },
  // 确认出价
  offerSureBtn: function(e) {
    console.log(e);
    var _this = this;
    var formId = e.detail.formId;
    app.postFormId(_this.data.token, formId);

    _this.setData({
      auction_gold_coin: e.detail.value.my_offer
    })
    var requestData = {
      token: _this.data.token,
      version: app.setConfig.version,
      type: app.setConfig.type,
      goods_id: _this.data.goodsId,
      auction_gold_coin: _this.data.auction_gold_coin
    }
    app.post('/Goods/auctionGoods', requestData, function(res) {
      if (res.code == 2000) {
        wx.showToast({
          title: '出价成功',
          icon: 'success',
          duration: 2000,
          success: function() {
            _this.setData({
              gold_coin: res.data.goods_gold_coin,
              isBiddersShow: 0
            })
          }
        })
      } else if (res.code == 3030) {
        wx.showModal({
          title: '提示',
          content: '金币不足',
          cancelText: '知道啦',
          confirmText: '去赚金币',
          success: function(res) {
            if (res.confirm) {
              wx.navigateTo({
                url: '/pages/getGold/getGold',
              })
            } else if (res.cancel) {}
          }
        })
      } else {
        wx.showToast({
          title: res.msg,
          icon: 'none',
          duration: 2000
        })
      }
    });
  },
  // 阻止事件冒泡
  preventEvent: function() {
    // 阻止事件冒泡
  },
  /*前往商品详情页面*/
  goDetail: function(e) {
    var goods_id = e.currentTarget.dataset.goods_id;
    wx.navigateTo({
      url: '/pages/goodsDetail/goodsDetail?goodsId=' + goods_id,
    })
  },
  // 免费领取
  freeReceive: function(e) {
    var _this = this;
    var formId = e.detail.formId;
    app.postFormId(_this.data.token, formId);
    if (_this.data.goodsType == 0) {
      var data = {
        'goods_num': 1,
        'goods_id': _this.data.goodsId,
        'buyType': 1, //0 表示直接购买1表示分享下单
        'selectAttributs': "",
        'goods_price': _this.data.selectAttributeprice
      }
      wx.setStorageSync('cookie', data)
      _this.checkAddress(1);
    } else {
      _this.setData({
        ischooseSizeShow: 1,
        btnType: 1
      })
    }
  },
  // 获取商品数量
  getGoodsNum: function(e) {
    var _this = this;
    var theGoodsNum = Number(e.detail.value);
    var total_num = Number(_this.data.total_num);
    if (theGoodsNum > total_num) {
      wx.showToast({
        title: '没有更多商品了哦~',
        icon: 'error',
        duration: 2000
      });
      _this.setData({
        goodsNum: total_num
      })
      return false;
    } else if (theGoodsNum < 1) {
      wx.showToast({
        title: '不能再少了哦~',
        icon: 'error',
        duration: 2000
      });
    } else {
      _this.setData({
        goodsNum: theGoodsNum
      })
    }

  },
  // 增加商品数量
  plus: function() {
    var _this = this;
    var theGoodsNum = _this.data.goodsNum;
    theGoodsNum++;
    var total_num = _this.data.total_num;
    var is_bargain = _this.data.is_bargain;
    var is_draw = _this.data.is_draw;
    if (is_draw == 1) {
      wx.showToast({
        title: '抽奖商品限购1份',
        icon: 'none',
        duration: 2000
      });
      return false;
    }
    if (is_bargain == 1) {
      wx.showToast({
        title: '砍价商品限购1份',
        icon: 'none',
        duration: 2000
      });
      return false;
    }

    if (theGoodsNum > total_num) {
      wx.showToast({
        title: '没有更多商品了哦~',
        icon: 'none',
        duration: 2000
      });
      return false;
    } else {
      _this.setData({
        goodsNum: theGoodsNum
      })
    }

  },
  // 减少商品数量
  reduce: function() {
    var _this = this;
    var theGoodsNum = _this.data.goodsNum;
    var is_bargain = _this.data.is_bargain;
    if (is_bargain == 1) {
      wx.showToast({
        title: '砍价商品限购1份',
        icon: 'none',
        duration: 2000
      });
      return false;
    }
    if (theGoodsNum > 1) {
      theGoodsNum = theGoodsNum - 1;
    } else {
      wx.showToast({
        title: '不能再少了哦~',
        icon: 'error',
        duration: 2000
      });
    }
    _this.setData({
      goodsNum: theGoodsNum
    })
  },
  // 显示规则弹层
  getRule: function() {
    var _this = this;
    _this.setData({
      isResultMaskShow: 1
    })
  },

  // 获取轮播图的索引
  getIndex: function(e) {
    var _this = this;
    _this.setData({
      index: e.detail.current + 1
    })
  },
  // 假数据轮播结束执行的函数
  animationfinish: function() {

  },
  // 获取商品详情
  getGoodsDetail: function() {
    var _this = this;
  
    var requestData = {
      version: app.setConfig.version,
      token: _this.data.token,
      goods_id: _this.data.goodsId,
      uid: _this.data.share_uid
    }
    app.post('/Goods/detail', requestData, function(res) {
      if (res.code == 2000) {
        var buy_price = res.data.goods.buy_price;
        var buy_price_show = buy_price;
        var attributeImage = res.data.goods.carousel_img.length > 0 ? _this.data.fileStaticUri + '/' + res.data.goods.carousel_img[0] : "";
        _this.setData({
          isLoading: 0,
          is_show_buy_btn: res.data.goods.is_show_buy_btn,
          is_bargain: res.data.goods.is_bargain,
          is_vip_goods: res.data.goods.is_vip_goods,
          is_open_shop: res.data.goods.is_open_shop,
          lucky_rule: res.data.goods.lucky_rule,
          cash: res.data.goods.cash,
          idolId: res.data.goods.uid,
          full_money: res.data.shop.money,
          user_level: res.data.user.level,
          car_shop_num: res.data.shop_cart.num,
          shop_cart_is_show: res.data.shop_cart.is_show,
          is_show: res.data.goods.is_show,
          goodsAttibutes: res.data.attributes,
          goodsAttibutesData: res.data.attributes,
          attributeImage: attributeImage,
          selectAttributeprice: res.data.goods.buy_price,
          is_draw: res.data.is_draw,
          original_price: res.data.goods.original_price,
          buy_price: res.data.goods.buy_price,
          fans_price: res.data.goods.fans_price,
          vip_price: res.data.goods.vip_price,
          attr_original_pric: res.data.goods.original_price,
          attr_fans_pric: res.data.goods.fans_price,
          attr_vip_pric: res.data.goods.vip_price,
          attr_broker_pric: res.data.goods.make_price,
          adv_solt: res.data.adv,
          total_num: res.data.goods.total_num,
          ruleList: res.data.rule,
          carousel_img: res.data.goods.carousel_img,
          shop: res.data.shop,
          shopImage: _this.data.fileStaticUri + "/" + res.data.goods.image,
          goods_level: res.data.goods.goods_level,
          address_default: res.data.goods.address_default,
          goods_name: res.data.goods.name,
          goods_describe: res.data.goods.describe,
          detail_img: res.data.goods.detail_img,
          share_title: res.data.share.title,
          share_path: res.data.share.page,
          share_img: _this.data.fileStaticUri + "/" + res.data.share.image,
          lucky_rule: res.data.goods.lucky_rule,
          is_draw: res.data.goods.is_draw
        });
        _this.getGoodsList();
        _this.biddersCountDown();
      } else {
        wx.showToast({
          title: res.msg,
          icon: "none",
          duration: 2000
        });
      }
    });
  },
  // 获取商品推荐列表
  getGoodsList: function() {
    var _this = this;
    var requestData = {
      token: _this.data.token,
      version: app.setConfig.version,
      type: app.setConfig.type,
      keywords: _this.data.goods_name,
      search_type: 0,
      page: _this.data.page
    }
    app.post('/Goods/recommend', requestData, function(res) {
      if (res.code == 2000) {
        wx.hideNavigationBarLoading(); //完成停止加载
        wx.stopPullDownRefresh(); //停止下拉刷新
        var goodsList = _this.data.goodsList;

        goodsList = goodsList.concat(res.data.list);
        _this.setData({
          page: res.data.page,
          goodsList: goodsList
        })
      } else {
        wx.showToast({
          title: res.msg,
          icon: "none",
          duration: 2000
        });
      }
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var _this = this;
    var time = util.formatTime(new Date());
    wx.getSystemInfo({
      success: function(res) {
        if (res.system.search('iOS') == -1) {
          _this.setData({
            isUseHttp: 1
          })
        } else {
          _this.setData({
            isUseHttp: 0
          })
        }
        var theWinHeight = res.windowHeight;
        var theWinWidth = res.windowWidth;
        _this.setData({

          winWidth: theWinWidth,
          winHeight: theWinHeight
        });
      }
    });
    wx.getStorageSync('adv_solt');
    console.log('uid', options);
    if (options.uid) {
      _this.setData({
        share_uid: options.uid
      });
    };
    console.log(_this.data.share_uid);
    if (options.goodsId) {
      _this.setData({
        goodsId: options.goodsId,
      })
    };
    var scene = decodeURIComponent(options.scene);
    if (scene && scene !== 'undefined') {
      var sceneParams = new Array();
      sceneParams = scene.split('#');
      _this.setData({
        share_uid: sceneParams[0],
        goodsId: sceneParams[1],
      })
    }
    app.checkAuthioze(success => {
      _this.loop();
      _this.isGetConfigs();
    }, fail => {
      //未授权提示用户授权
      _this.setData({
        displayAuthShow: 1
      });
    });
  },

  // 判断是否获取到token的值了
  loop: function() {
    var _this = this;
    var theToken = wx.getStorageSync("token");
    if (!theToken) {
      setTimeout(function() {
        _this.loop()
      }, 100);
    } else {
     _this.setData({
       token: theToken
     })
      _this.getGoodsDetail();
    }
  },
  // 检测是否获取到本地缓存了
  isGetConfigs:function(){
    var _this = this;
    var configs = wx.getStorageSync('configs');
    var adv_solt = wx.getStorageSync('adv_solt');
    if (!configs) {
      setTimeout(function () {
        _this.isGetConfigs()
      }, 100);
    } else {
    _this.setData({
      service_goods_detail_is_show: configs.service_goods_detail_is_show,
      service_content: configs.service_content,
      service_reply_btn_title: configs.service_reply_btn_title,
      bargain_buy_title: configs.bargain_buy_title,
      draw_buy_title: configs.draw_buy_title,
      configs: configs,
      fileStaticUri: configs.static_url_http,
      filesSourceUri: configs.static_url_http,
      localSourceUri: configs.static_url_http,
      goods_page_top_adv_is_show: configs.goods_page_top_adv_is_show,
      user_nick: configs.user_nick,
      user_image: configs.user_image
    });
    }
  },
  /*角色权限控制*/
  getUserInfo: function (e) {
    var that = this;
    var infoUser = e.detail.userInfo;
    var res = e.detail;
    var url = app.setConfig.url + '/Login/doLogin';
    that.setData({
      displayAuthShow: 0,
      isGetInfo: 1
    });
    var data = {
      user_name: infoUser.nickName,
      nick_name: infoUser.nickName,
      head_img: infoUser.avatarUrl,
      sex: infoUser.gender,
      coutry: infoUser.country,
      city: infoUser.city,
      province: infoUser.province,
      code: app.globalData.code,
      encryptedData: res.encryptedData,
      signature: res.signature,
      ctype: app.setConfig.type,
      version: app.setConfig.version,
      iv: res.iv,
    }
    app.postLogin(url, data, function () {
      var cash = wx.getStorageSync('cash');
      if (cash != "") {
        that.setData({
          displayAuthShow: 0,
          isfriendShareMaskShow: 1,
          cash: cash
        })
      }
      that.loop();
      that.isGetConfigs();
    });
  },
  authRest: function () {
    this.setData({
      displayAuthShow: 0
    });
    setTimeout(function () {
      wx.reLaunch({
        url: '/pages/bargain/bargain',
      })
    }, 1000)
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    var _this = this;
    _this.setData({
      ischooseSizeShow: 0,
      isClick: 1,
      clickNum: 0,
      selectedAttributs: []
    });
    var goodsId;
    goodsId = _this.data.goodsId;
    if (!goodsId) {
      setTimeout(function() {
        goodsId = _this.data.goodsId;
      }, 100)
    } else {
      _this.loop();
      _this.isGetConfigs();
    }
    wx.showShareMenu({
      withShareTicket: true
    });
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    var _this = this;
    wx.showNavigationBarLoading() //在标题栏中显示加载
    _this.setData({
      goodsList: [], //存储首页书籍列表
      page: 1
    })
    _this.getGoodsList();
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {
    var _this = this;
    // console.log('1');
    _this.getGoodsList();
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function(options) {
    var _this = this;
    //获取分享按钮的分享类型 ，助力分享还是普通商品分享
    var sharetype = options.target.dataset.sharetype;
    var path, title, share_img;
    //助力分享
    title = _this.data.share_title;
    path = _this.data.share_path;
    share_img = _this.data.share_img;
    return {
      title: title,
      path: path,
      imageUrl: share_img,
      success: function(res) {
        wx.showToast({
          title: '分享成功',
          duration: 2000,
          icon: "none"
        })
      },
      fail: function(err) {
        console.log(err);
      }
    }
  },
  /*返回主页*/
  goHome: function() {
    wx.reLaunch({
      url: '/pages/home/home',
    })
  },
  /*直接购买商品*/
  goBuy: function(e) {
    var _this = this;
    var formId = e.detail.formId;
    app.postFormId(_this.data.token, formId);
    var goods_id = _this.data.goodsId;
    if (_this.data.goodsType > 0) {
      _this.setData({
        isHasChoosed: 1,
        ischooseSizeShow: 1,
        btnType: 0
      });
    } else {
      var buy_num = _this.data.goodsNum;
      var data = {
        'goods_num': 1,
        'goods_id': _this.data.goodsId,
        'buyType': 0, //0 表示直接购买1表示分享下单
        'selectAttributs': "",
        'goods_price': _this.data.selectAttributeprice
      }
      wx.setStorageSync('cookie', data)
      _this.checkAddress(0);
    }
  },
  /*选择属性值事件*/
  selectAttributeEvent: function(e) {
    var _this = this;
    if (e.type == "tap") {
      var attr_id = e.currentTarget.dataset.attr_id;
      var goods_attr_id = e.currentTarget.dataset.goods_attr_id;
      var goodsAttibutes = _this.data.goodsAttibutes;
      var attrThumb = e.currentTarget.dataset.thumb;
      var attrPric = e.currentTarget.dataset.attr_pric; //属性优品价格
      var attr_original_pric = e.currentTarget.dataset.attr_original_pric; //商品原价
      var attr_fans_pric = e.currentTarget.dataset.attr_fans_pric; //属性粉丝价
      var attr_vip_pric = e.currentTarget.dataset.attr_vip_pric; //属性会员价
      var attr_broker_pric = e.currentTarget.dataset.attr_broker_pric; //属性用金价
      var attr_num = e.currentTarget.dataset.attr_num; //属性个数
      // console.log(attr_num);
      var goodsNum = _this.data.goodsNum;
      if (goodsNum > attr_num) {
        wx.showToast({
          title: '购买数量不得大于库存',
          icon: 'none',
          duration: 2000,
          success: function() {
            _this.setData({
              goods_attr_id: goods_attr_id,
              goodsNum: attr_num,
              total_num: attr_num
            })
          }
        })
      } else {
        _this.setData({
          goods_attr_id: goods_attr_id,
          total_num: attr_num
        })
      }
      var newGoodsAttributes = [];
      goodsAttibutes.forEach((currentValue, index, goodsAttibutes) => {
        if (attr_id == currentValue.attr_id) {
          var newAttrExt = [];
          currentValue.attr_ext.forEach((currentExtValue, extIndex) => {
            if (currentExtValue.goods_attr_id == goods_attr_id) {
              if (currentExtValue.is_selected == 0) {
                //获取已选择的属性分类
                var selectedAttributs = _this.data.selectedAttributs;
                if (!selectedAttributs.in_array(currentExtValue.attr_name)) {
                  selectedAttributs.push(currentExtValue.attr_name);
                  _this.setData({
                    selectedAttributs: selectedAttributs
                  });
                }
                currentExtValue.is_selected = 1;
                _this.uploadTips(currentExtValue.attr_name, 1);
                if (attrPric > 0.00) {
                  if (_this.data.goods_level == 2 || _this.data.goods_level == 3) {
                    attrPric = e.currentTarget.dataset.attr_pric;
                  }
                  _this.setData({
                    selectAttributeprice: attrPric,
                  });
                }
                if (attrThumb) {
                  _this.setData({
                    attributeImage: _this.data.fileStaticUri + '/' + attrThumb
                  });
                }
              } else {
                var selectedAttributs = _this.data.selectedAttributs;
                if (selectedAttributs.in_array(currentExtValue.attr_name)) {
                  selectedAttributs.remove(currentExtValue.attr_name);
                  _this.setData({
                    selectedAttributs: selectedAttributs
                  });
                }
                currentExtValue.is_selected = 0;
                _this.uploadTips(currentExtValue.attr_name, 0);
                var selectAttributeprice = _this.data.buy_price;
                if (_this.data.goods_level == 2 || _this.data.goods_level == 3) {
                  selectAttributeprice = _this.data.goods.buy_price;
                }
                _this.setData({
                  selectAttributeprice: selectAttributeprice,
                  attributeImage: _this.data.initThumb
                });
              }
            } else {
              currentExtValue.is_selected = 0;
            }
            newAttrExt.push(currentExtValue);
          });
          currentValue.attr_ext = newAttrExt;
          newGoodsAttributes.push(currentValue);
        } else {
          newGoodsAttributes.push(currentValue);
        }
      });

      _this.setData({
        attr_original_pric: attr_original_pric,
        goodsAttibutes: newGoodsAttributes,
        attr_fans_pric: attr_fans_pric,
        attr_vip_pric: attr_vip_pric,
        attr_broker_pric: attr_broker_pric
      });
    }
    //更新选择的属性值
    _this.uploadSelectAttributes();
    if (_this.data.attributeImage == '') {
      _this.setData({
        attributeImage: _this.data.fileStaticUri + '/' + _this.data.carousel_img[0]
      })

    }
  },
  /*更新选择的属性*/
  uploadSelectAttributes: function() {
    var _this = this;
    var goodsAttibutes = _this.data.goodsAttibutes;
    var selectAttrips = "";
    goodsAttibutes.forEach((attribute, index) => {
      attribute.attr_ext.forEach((v, i) => {
        if (v.is_selected == 1) {
          selectAttrips = selectAttrips + " " + v.attr_value
        }
      });
    });
    _this.setData({
      selectAttributs: selectAttrips
    });
    if (!_this.data.selectTips) {
      _this.setData({
        selectTips: selectAttrips,
        selectTipsTitle: '已选择'
      })
    }
  },
  /*尝试更新提示状态*/
  uploadTips: function(attr_name, is_selected) {
    var _this = this;
    var runSelectTips = _this.data.runSelectTips;
    var newRunSelectTips = [];
    runSelectTips.forEach((v, index) => {
      if (is_selected == 1) {
        if (v.attr_name == attr_name) {
          newRunSelectTips.push({
            attr_name: v.attr_name,
            is_selected: 1
          })
        } else {
          newRunSelectTips.push({
            attr_name: v.attr_name,
            is_selected: v.is_selected
          })
        }
      } else {
        //取消选择
        if (v.attr_name == attr_name) {
          newRunSelectTips.push({
            attr_name: v.attr_name,
            is_selected: 0
          })
        } else {
          newRunSelectTips.push({
            attr_name: v.attr_name,
            is_selected: v.is_selected
          })
        }
      }
    });
    _this.setData({
      runSelectTips: newRunSelectTips
    })
    this.refreshTips();
  },

  //创建订单按钮事件
  createOrderEvent: function(e) {
    //检查订单是否为分享订单
    var _this = this;
    var formId = e.detail.formId;
    app.postFormId(_this.data.token, formId);
    var share_num = _this.data.share_num;
    var selectTips = "";
    var checkResult = _this.checkGoodsAttribute();
    if (checkResult <= 0) {
      _this.createOrder();
    } else {
      var tips = "";
      checkResult.forEach((result, index) => {
        tips = tips + " " + result;
      });
      new app.ToastPannel();
      this.show("请选择：" + tips);
    }
  },
  //检查属性选择情况
  checkGoodsAttribute: function() {
    var _this = this;
    //获取必选项的数据
    var selectedMust = [];
    _this.data.goodsAttibutes.forEach((attributes, index) => {
      if (attributes.is_required == 1) {
        if (!selectedMust.in_array(attributes.attr_name)) {
          selectedMust.push(attributes.attr_name);
        }
      }
    });
    return selectedMust.difference(_this.data.selectedAttributs);
  },
  //开始创建订单
  createOrder: function() {
    var _this = this;
    if (this.data.btnType == 1) {
      var buy_num = _this.data.goodsNum;
      var data = {
        'goods_num': buy_num,
        'goods_id': _this.data.goodsId,
        'buyType': 1, //0 表示直接购买1表示分享下单
        'selectAttributs': _this.data.selectAttributs,
        'goods_price': _this.data.selectAttributeprice
      }
      wx.setStorageSync('cookie', data)
      _this.checkAddress(1);
    } else {
      var buy_num = _this.data.goodsNum;
      var data = {
        'goods_num': buy_num,
        'goods_id': _this.data.goodsId,
        'buyType': 0, //0 表示直接购买1表示分享下单
        'selectAttributs': _this.data.selectAttributs,
        'goods_price': _this.data.selectAttributeprice
      }
      wx.setStorageSync('cookie', data);
      _this.checkAddress(0);
    }
  },
  /*检查用户地址*/
  checkAddress: function(buyType) {
    var _this = this;
    // 当前页面选择过尺寸
    if (buyType == 0) {
      // 直接购买的商品
      if (this.data.address_default == 0) {
        // 没有默认地址跳转添加地址页
        wx.navigateTo({
          url: '/pages/addAddress/addAddress?goodsid=' + _this.data.goodsId + "&buyType=" + buyType + "&lucky_id=" + _this.data.lucky_id + "&draw_goods_id=" + _this.data.draw_goods_id,
        });
        return false;
      } else {
        //已经存在默认收货地址
        var cookie = wx.getStorageSync('cookie');
        return true;
      }
    } else {
      // 分享的商品
      if (this.data.default_address == 0) {
        wx.navigateTo({
          url: '/pages/addAddress/addAddress?goodsid=' + _this.data.goodsId + "&buyType=" + buyType,
        });
        return false;
      } else {
        var requestData = {
          token: _this.data.token,
          goods_id: _this.data.goodsId,
          attr_values: _this.data.selectAttributs,
          lucky_id: _this.data.lucky_id,
          draw_goods_id: _this.data.draw_goods_id
        }
        app.post('/Goods/getGoods', requestData, function(res) {
          if (res.code == 2000) {
            wx.navigateTo({
              url: '/pages/orderDetail/orderDetail?orderId=' + res.last_id,
            })
          } else {
            new app.ToastPannel();
            _this.show(res.msg);
            wx.showToast({
              title: res.msg,
              icon: "none",
              duration: 2000
            });
          }
        });
      }
    }
  },
  //提示分享到群
  shareGroupEvent: function(e) {
    var _this = this;
    _this.setData({
      share_num: 0
    });
  },
  //加金币默认提示
  goldAddEvent: function(e) {
    var _this = this;
    var gold_num_tips = _this.data.gold_num_tips;
    var gold_share_default_tips = _this.data.gold_share_default_tips;
    _this.setData({
      isShareTipsShow: 1,
      gold_num_tips: gold_share_default_tips
    });
    setTimeout(function() {
      _this.setData({
        isShareTipsShow: 0,
        gold_num_tips: gold_num_tips
      });
    }, 2000);
  },
  goIndexEvent: function() {
    wx.reLaunch({
      url: '/pages/home/home',
    });
  },
  // 点击竞拍按钮
  biddersEvent: function(e) {
    var _this = this;
    var formId = e.detail.formId;
    app.postFormId(_this.data.token, formId);
    _this.setData({
      isBiddersShow: 1
    })
  },
  //免费领表单提交
  buyFreeSubmitEvent: function(e) {
    var that = this;
    var formId = e.detail.formId;
    app.postFormId(that.data.token, formId);
    that.isChooseSize();
    var goods_id = that.data.goodsId;
    // 获取商品型号列表
    var goodsAttibutes = that.data.goodsAttibutes;
    if (goodsAttibutes.length == 0) {
      //获取商品类型 
      var get_type = that.data.get_type;
      if (get_type == 0) {
        // 一口价 平台订单
        wx.navigateTo({
          url: '/pages/orderDetail/orderDetail',
        })
      } else if (get_type == 1) {

      } else if (get_type == 2) {
        //助力
        var help_num = that.data.help_num;
        if (help_num == 0) {
          wx.navigateTo({
            url: '/pages/orderDetail/orderDetail',
          })
        } else {
          if (that.data.helpBoxShow == 1) {
            that.setData({
              helpBoxShow: 0
            });
          } else {
            that.setData({
              helpBoxShow: 1
            });
          }
        }

      }
    } else {
      that.setData({
        ischooseSizeShow: 1
      })
    }
  },
  //创建剩余助力人数数组
  unhelp_user_list: function(num) {
    var unhelp_user_list = [];
    for (var i = 0; i < num; i++) {
      unhelp_user_list[i] = i;
    }
    this.setData({
      unhelp_user_list: unhelp_user_list
    });
  },
  /*助力免费领 免费领取*/
  goBuyFree: function(e) {
    var that = this;
    if (that.data.orderId > 0) {
      wx.navigateTo({
        url: '/pages/orderDetail/orderDetail?orderId=' + that.data.orderId,
      })
    }
  },
  //编辑
  editEvent: function(e) {
    var that = this;
    var formId = e.detail.formId;
    app.postFormId(that.data.token, formId);
    wx.navigateTo({
      url: '/pages/releaseGood/releaseGood?goodsId=' + that.data.goodsId,
    })
  },
  //前往个人详情页面
  goUserInfoEvent: function() {
    var that = this;
    var shopId = this.data.shopId;
    wx.navigateTo({
      url: '/pages/myHomePage/myHomePage?uid=' + that.data.shopId + '&goodsId=' + that.data.goodsId,
    })
  },
  /*红包广告跳转事件*/
  goAdvEvent: function(e) {
    var _this = this;
    var adv_solt = _this.data.adv_solt;
    if (_this.data.adv_solt) {
      //广告数据不为空
      if (adv_solt.adv_type == 1) {
        //图片类
        wx.navigateTo({
          url: '/pages/rule/rule?url=' + adv_solt.adv_info_url
        });
      } else if (adv_solt.adv_type == 3) {
        //小程序类
        wx.navigateToMiniProgram({
          appId: adv_solt.app_id.toString(),
          path: adv_solt.page.toString(),
          extraData: adv_solt.sence.toString(),
          complete(res) {
            console.log(res)
          }
        });
      } else {
        //内部网页类型
        wx.navigateTo({
          url: "/" + adv_solt.adv_uri,
        })
      }
    }
  },
  // 竞拍倒计时
  biddersCountDown: function() {
    var _this = this;
    var auction_end_time = _this.data.auction_end_time;
    var totalSecond = auction_end_time - Date.parse(new Date()) / 1000;

    var interval = setInterval(function() {
      // 秒数
      var second = totalSecond;

      // 天数位
      var day = Math.floor(second / 3600 / 24);
      var dayStr = day.toString();
      if (dayStr.length == 1) dayStr = '0' + dayStr;

      // 小时位
      var hr = Math.floor((second - day * 3600 * 24) / 3600);
      var hrStr = hr.toString();
      if (hrStr.length == 1) hrStr = '0' + hrStr;

      // 分钟位
      var min = Math.floor((second - day * 3600 * 24 - hr * 3600) / 60);
      var minStr = min.toString();
      if (minStr.length == 1) minStr = '0' + minStr;

      // 秒位
      var sec = second - day * 3600 * 24 - hr * 3600 - min * 60;
      var secStr = sec.toString();
      if (secStr.length == 1) secStr = '0' + secStr;

      this.setData({
        countDownDay: dayStr,
        countDownHour: hrStr,
        countDownMinute: minStr,
        countDownSecond: secStr,
      });
      totalSecond--;
      if (totalSecond < 0) {
        clearInterval(interval);
        _this.setData({
          auction_status: 2
        })
        this.setData({
          countDownDay: '00',
          countDownHour: '00',
          countDownMinute: '00',
          countDownSecond: '00',
        });
      }
    }.bind(this), 1000);
  },
  // 点击获取生成二维码按钮
  gerQrcode: function(e) {
    var _this = this;
    var formId = e.detail.formId;
    app.postFormId(_this.data.token, formId);
    _this.getQRCodeImg();
    _this.setData({
      isQRCodeMaskShow: 1,
      isShareMaskShow: 0
    })
  },
  // 获取二维码图片
  getQRCodeImg: function() {
    var _this = this;
    var requestData = {
      token: _this.data.token,
      version: app.setConfig.version,
      type: app.setConfig.type,
      goods_id: _this.data.goodsId
    }
    app.post(getQRCodeImgUrl, requestData, function(res) {
      if (res.code == 2000) {
        _this.setData({
          QRCodeImg: res.data.image,
          QRCodeImgHttp: res.data.image_http
        })
      } else {
        wx.showToast({
          title: res.msg,
          icon: "none",
          duration: 2000
        });
      }
    })
  },
  // 保存图片
  saveImg: function(e) {
    var _this = this;
    var formId = e.detail.formId;
    app.postFormId(_this.data.token, formId);
    wx.downloadFile({
      url: _this.data.QRCodeImg,
      success: function(res) {
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success: function(res) {
            wx.showToast({
              title: '图片保存成功',
              icon: 'success',
              duration: 2000
            })
          },
          fail: function(res) {
            console.log(res)
            console.log('fail')
          }
        })
      },
      fail: function() {
        console.log('fail')
      }
    })
  },
  // 预览图片
  previewImg: function() {
    var _this = this;
    var urls;
    if (_this.data.isUseHttp == 1) {
      urls = [_this.data.QRCodeImgHttp]
    } else {
      urls = [_this.data.QRCodeImg]
    }
    wx.previewImage({
      current: _this.data.QRCodeImg, // 当前显示图片的http链接
      urls: urls
    })
  },
  // 关闭分享二维码弹层
  closeQRCodeMask: function() {
    this.setData({
      isQRCodeMaskShow: 0
    })
  }
})